package everyday;

import CommonStructure.TreeNode;

public class T1373 {
    int max = 0, MAX = Integer.MAX_VALUE, MIN = Integer.MIN_VALUE;
    public int maxSumBST(TreeNode root) {
        dfs(root);
        return max;
    }
    private int[] dfs(TreeNode node){
        if(node == null) return new int[]{0,MIN,MAX};
        int[] l = dfs(node.left), r = dfs(node.right);
        if((node.left == null || node.val > l[1]) &&
                (node.right == null || node.val < r[2]) && l[0] != MAX && r[0] != MAX) {
            if(node.val + l[0] + r[0] > max) max = node.val + l[0] + r[0];
            return new int[]{node.val + l[0] + r[0],Math.max(node.val,Math.max(l[1],r[1])),Math.min(node.val,Math.min(l[2],r[2]))};
        }
        return new int[]{MAX,0,0};
    }
}
